package com.example.love24handroid;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class upAvatar extends Activity implements OnClickListener {

	Button btnUpload, btnUp; // Nut de upload anh
	private Bitmap bitmap; // Anh se dua len server
	private ImageView imagefile; // Anh de nhin truoc khi upload len
	private static final int PICK_IMAGE = 1; // So luong image duoc lay tu Galery
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.upimagexml);
		imagefile = (ImageView) findViewById(R.id.imagefile);
		btnUpload = (Button) findViewById(R.id.btnUpload);
		btnUp = (Button) findViewById(R.id.btnUp);
		btnUpload.setOnClickListener(this);
		btnUp.setOnClickListener(this);
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		switch(v.getId())
		{
		case R.id.btnUpload:
			// Make Image from galery
			selectedImageFromGalery();
			break;
		case R.id.btnUp:
			try
			{
			 new uploadImageToServer().execute();
			}
			
			catch (Exception e) {
			    // something went wrong. connection with the server error
				
			}
		default:
			break;
		}
	}
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == PICK_IMAGE  && resultCode == RESULT_OK && null != data )
		{
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };
			Cursor cursor = getContentResolver().query(selectedImage,
		    filePathColumn, null, null, null);
		   cursor.moveToFirst();

		   int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
		   String picturePath = cursor.getString(columnIndex);
		   cursor.close();
		   
		   decodeFile(picturePath);
		}
		
	}
	
	 public void decodeFile(String filePath) {
		  // Decode dung luong anh
		  BitmapFactory.Options o = new BitmapFactory.Options();
		  o.inJustDecodeBounds = true;
		  BitmapFactory.decodeFile(filePath, o);

		  // Kich thuoc anh
		  final int REQUIRED_SIZE = 1024;

		  // Tim kich thuoc anh thuc
		  int width_tmp = o.outWidth, height_tmp = o.outHeight;
		  int scale = 1;
		  while (true) {
		   if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
		    break;
		   width_tmp /= 2;
		   height_tmp /= 2;
		   scale *= 2;
		  }

		  // Decode voi inSampleSize
		  BitmapFactory.Options o2 = new BitmapFactory.Options();
		  o2.inSampleSize = scale;
		  bitmap = BitmapFactory.decodeFile(filePath, o2);
		  
		  // Dua ra bitmap de hien thi
		  imagefile.setImageBitmap(bitmap);
		 }
	
	 // Select 1 anh trong galery cua dt
	public void selectedImageFromGalery()
	{
		Intent intent1 = new Intent();
		intent1.setType("image/*");
		intent1.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(Intent.createChooser(intent1, "Select Picture"),PICK_IMAGE);
	}
	
	// Upload anh len server su dung thread
	class uploadImageToServer extends AsyncTask<Void, Void, String> 
	{
		private ProgressDialog dialog = new ProgressDialog(upAvatar.this);
		@Override
		protected String doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			
			try {
				 HttpPost httppost = new HttpPost("http://api.love24h.net/"); // Or HttpPost(), depends on your needs
				 String credentials = "love24h_test" + ":" + "e7d5554ed2b3cc3f1bebbd4ad122382f";
				 String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
				 httppost.addHeader("Authorization", "Basic " + base64EncodedCredentials);		
				 
				 
				 // cai nay dang test
				 Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
				
				 ByteArrayOutputStream bos = new ByteArrayOutputStream();
				 bitmapOrg.compress(CompressFormat.JPEG, 100, bos);		
				
				    byte[] _data = bos.toByteArray();
				    String ba1 = Base64.encodeToString(_data, Base64.NO_WRAP);
				  
				 // Su dung method post de dang nhap
				 // Dung Json
				 // Chuyen cac du lieu sang dang Json
				  JSONObject json = new JSONObject();
				  json.put("act", "upload");
				  json.put("image", ba1);
				  json.put("email", "test@love24h.net" );
		          json.put("password", "volgatroidep");
		          String data = json.toString();  
		          Log.e("Warning! ", data);
		         
		          String base64 = Base64.encodeToString(data.getBytes("utf-8"), Base64.NO_WRAP ); //(, Base64.DEFAULT);
		          
		          // Chuyen du lieu vao mang va dua len server
		          ArrayList<NameValuePair> nameValuePairs = new
				    	     ArrayList<NameValuePair>();
				    
				  nameValuePairs.add(new BasicNameValuePair("data",base64));	          
			    

			    HttpClient httpclient = new DefaultHttpClient();
	    		httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	    		//  httppost.setHeader("Content-type", "application/json");
	    		   HttpResponse res = httpclient.execute(httppost);
	    		   
	    		   HttpEntity entity = res.getEntity();
	    		  InputStream  is = entity.getContent();
	    		   
	    		   BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
	    		   StringBuilder sb = new StringBuilder();
	    		   String line = null;
	    		   while ((line = reader.readLine()) != null)
		    		   {
		  				sb.append(line + "\n");
		    		   }
	    		   is.close();
	    		   Log.e("Res 1: ", sb.toString());
				return "Ban da dang nhap thanh cong!";
			   } catch (Exception e) {
			    // upload error
			   }
			
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			 dialog.dismiss();
			 Toast.makeText(getApplicationContext(), "Image uploaded ...",Toast.LENGTH_LONG).show();
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			 dialog.setMessage("Uploading image to server ...");
			 dialog.show();
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}
		
	}
	
	
}
